<?php

/**
 * UserIdentity represents the data needed to identity a user.
 * It contains the authentication method that checks if the provided
 * data can identity the user.
 */
class UserIdentity extends CUserIdentity
{
    private $_id;
    public $userType = 'Front';

    /**
     * Authenticates a user.
     * @return boolean whether authentication succeeds.
     */
    public function authenticate()
    {
        if ($this->userType == 'Front') { // This is front login
            $user = Users::model()->find('LOWER(email)=?', array(strtolower($this->username)));
            if ($user === null)
                $this->errorCode = self::ERROR_USERNAME_INVALID;
            else if (!$user->validatePassword($this->password))
                $this->errorCode = self::ERROR_PASSWORD_INVALID;
            else {
                $this->_id = $user->id;
                $this->username = $user->email;
                $this->errorCode = self::ERROR_NONE;
            }
        }

        if ($this->userType == 'Back') // This is admin login
        {
            // check if login details exists in database
            $record = Users::model()->findByAttributes(array('username' => $this->username, 'role'=> 1, 'status' => 1)); // here I use username as user name which comes from database
            if ($record === null) {
                $this->errorCode = self::ERROR_USERNAME_INVALID;
            } else if ($record->password !== md5($this->password)) // let we have base64_encode password in database
            {
                $this->errorCode = self::ERROR_PASSWORD_INVALID;
            } else {
                $this->_id = $record->id;
                Yii::app()->user->setState('isAdmin', 1);
                Yii::app()->user->setState('name', $record->username);
                Yii::app()->user->setState('roles', 'admin');

                /*$this->setState('isAdmin', 1);
                $this->setState('userId', $record->id);
                $this->setState('name', $record->email);*/
                $this->errorCode = self::ERROR_NONE;
            }
        }
        return $this->errorCode == self::ERROR_NONE;
    }

    /**
     * @return integer the ID of the user record
     */
    public function getId()
    {
        return $this->_id;
    }
}